import React, { PureComponent } from "react";
import {
  Text,
  View,
  Image,
  TextInput,
  Alert,
  ScrollView,
  FlatList,
  TouchableOpacity,
  Keyboard,
  StyleSheet,
  Platform
} from "react-native";
import {
  statusBarHeight,
  safeAreaBottomHeight,
  LoginToken,
  screenHeight
} from "../../util/AdapterUtil";
import NavigationService from "../../components/NavigationService";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import actions from "../../models/actions";
import * as httpUtils from "../../util/httpUtils";
import { connect } from "react-redux";
import NavigationBar from "../../components/navigationBar";
import { StackActions } from "react-navigation";
import image from "../../assets/image";
import ImagePicker from "react-native-image-picker";
import payment_record from "../../assets/images/payment_record.png";
import * as requestApi from "../../util/requestApi";
import { QNEngine } from "../../native/QNEngine";

class PayResultScreen extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      remarks: "",
      images: [], //本地图片数组
      pics: [] //七牛图片数组
    };
  }

  componentWillUnmount() {}

  componentDidMount() {
    //七牛的原生通知统一管理
    QNEngine.eventEmitter({
      onProgress: data => {
        console.log(data.percent);
      },
      onComplete: data => {
        if (Platform.OS == "ios") {
          console.log(data);
        } else {
          console.log(data.key);
        }
        let newPics = [...this.state.pics];
        if (Platform.OS == "ios") {
          newPics.push(data.msg);
        } else {
          newPics.push(data.key);
        }
        this.setState({
          pics: newPics
        });

        if (newPics.length == this.state.images.length) {
          //全部上传成功
          this.gocommint(); //提交内容
        }
      },
      onError: data => {
        console.log(data);
        switch (data.code) {
          case "-2":
            Toast.show("任务已暂停");
            break;
          default:
            Toast.show("错误：" + data.msg);
            break;
        }
      }
    });
  }

  componentWillUnmount() {
    QNEngine.removeEmitter();
  }

  render() {
    return (
      <View style={{ flex: 1, backgroundColor: "#F9F9F9" }}>
        <NavigationBar
          navigation={this.props.navigation}
          isBack={true}
          title={"支付结果"}
        />
        <KeyboardAwareScrollView style={{ flex: 1 }}>
          <View
            style={{
              marginTop: 8,
              backgroundColor: "#fff",
              flex: 1,
              paddingLeft: 20,
              paddingRight: 15,
              paddingBottom: 15,
              alignItems: "center",
              justifyContent: "center"
            }}
          >
            <Image
              source={image.safetypay}
              style={{
                marginTop: 30,
                width: 60,
                height: 60
              }}
            />

            <Text
              style={{
                marginTop: 20,
                color: "#4A90E2",
                fontSize: 18,
                fontWeight: "bold"
              }}
            >
              支付成功
            </Text>
            <Text
              style={{
                marginTop: 20,
                color: "#4A4A4A",
                fontSize: 18,
                fontWeight: "bold"
              }}
            >
              {this.props.navigation.state.params.money}元
            </Text>
            <Text
              style={{
                marginTop: 10,
                color: "#606060",
                fontSize: 16
              }}
            >
              收款方：{this.props.navigation.state.params.companyName}
            </Text>
          </View>

          <View
            style={{
              marginTop: 8,
              backgroundColor: "#fff",
              flex: 1,
              paddingLeft: 20,
              paddingRight: 15,
              paddingBottom: 15
            }}
          >
            <View
              style={{
                backgroundColor: "#fff",
                flexDirection: "row",
                height: 40,
                alignItems: "center",
                justifyContent: "center"
              }}
            >
              <View
                style={{
                  height: 1,
                  flex: 1,
                  backgroundColor: "#ccc",
                  transform: [{ scaleY: 0.5 }]
                }}
              />
              <Text
                style={{
                  marginLeft: 10,
                  marginRight: 10,
                  color: "#606060",
                  fontSize: 18
                }}
              >
                支付单备注
              </Text>
              <View
                style={{
                  height: 1,
                  flex: 1,
                  backgroundColor: "#ccc",
                  transform: [{ scaleY: 0.5 }]
                }}
              />
            </View>

            <TextInput
              style={{
                padding: 0,
                color: "#202020",
                fontSize: 16,
                flex: 1,
                minHeight: 40,
                alignItems: "center"
              }}
              placeholder={"请输入支付单备注"}
              selectionColor={"#4A90E2"}
              maxLength={150}
              onChangeText={text =>
                this.setState({
                  remarks: text
                })
              }
              multiline={true}
            />

            <ScrollView
              ref={e => {
                 this.scrollView = e;
              }}
              style={{
                marginTop: 30,
                backgroundColor: "#fff",
                height: 50
              }}
              horizontal={true}
              onScroll = {(event)=>{{
                  let OffsetX = event.nativeEvent.contentOffset.x
                  console.log(OffsetX);//水平滚动距离
                  console.log(event.nativeEvent.contentOffset.y);//垂直滚动距离
                  if (Platform.OS == "android" && OffsetX < 0 &&  this.scrollView) {
                      this.scrollView.scrollTo({ x: -OffsetX, y: 0 });
                  }
              }}}
            >
              <FlatList
                style={{ backgroundColor: "#fff" }}
                scrollEnabled={false}
                data={this.state.images}
                horizontal={true}
                keyExtractor={(item, index) => index.toString()}
                renderItem={({ item, index }) => {
                  return (
                    <View
                      style={{
                        borderRadius: 2,
                        marginLeft: 10,
                        width: 45,
                        height: 45
                      }}
                    >
                      <Image
                        source={{ uri: item }}
                        resizeMode={"cover"}
                        style={{ borderRadius: 2, width: 45, height: 45 }}
                      />
                      <TouchableOpacity
                        style={{
                          position: "absolute",
                          top: 0,
                          right: 0,
                          borderRadius: 7,
                          borderWidth: 1,
                          width: 14,
                          height: 14,
                          borderColor: "red",
                          backgroundColor: "red",
                          justifyContent: "center",
                          alignItems: "center"
                        }}
                        onPress={() => {
                          this.deleteImage(index);
                        }}
                      >
                        <Image
                          source={image.ic_close}
                          style={{ width: 8, height: 8 }}
                        />
                      </TouchableOpacity>
                    </View>
                  );
                }}
              />
              {this.state.images.length < 10 ? (
                <TouchableOpacity
                  style={{
                    marginLeft: 10,
                    height: 45,
                    width: 45,
                    borderRadius: 3,
                    borderWidth: 1,
                    borderColor: "#DDDDDD",
                    backgroundColor: "#fff",
                    justifyContent: "center",
                    alignItems: "center"
                  }}
                  onPress={this.launchImageLibrary.bind(this)}
                >
                  <Text style={{ color: "#DDDDDD", fontSize: 18 }}>+</Text>
                </TouchableOpacity>
              ) : null}
            </ScrollView>
          </View>

          <TouchableOpacity
            style={{
              marginTop: 30,
              marginLeft: 20,
              marginRight: 20,
              height: 45,
              borderRadius: 3,
              borderWidth: 1,
              borderColor: "#4A90E2",
              backgroundColor: "#fff",
              justifyContent: "center",
              alignItems: "center"
            }}
            onPress={this.photograph.bind(this)}
          >
            <Text style={{ color: "#4A90E2", fontSize: 14 }}>拍照备注</Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={{
              marginTop: 15,
              marginLeft: 20,
              marginRight: 20,
              height: 45,
              borderRadius: 3,
              backgroundColor: "#3591FF",
              justifyContent: "center",
              alignItems: "center"
            }}
            onPress={() => {
              this.getQiniuToken();
            }}
          >
            <Text style={{ color: "#fff", fontSize: 14 }}>提交</Text>
          </TouchableOpacity>
        </KeyboardAwareScrollView>
        <View style={{ height: safeAreaBottomHeight }} />
      </View>
    );
  }

  //拍照
  photograph() {
    if (this.state.images.length >= 10) {
      Toast.show("最多添加10张图片", 1000);
      return;
    }
    var options = {
      title: "图片来源", // 选择器的标题，可以设置为空来不显示标题
      cancelButtonTitle: "取消",
      takePhotoButtonTitle: "照相机", // 调取摄像头的按钮，可以设置为空使用户不可选择拍照
      chooseFromLibraryButtonTitle: "相册", // 调取相册的按钮，可以设置为空使用户不可选择相册照片
      mediaType: "photo", // 'photo' or 'video'
      maxWidth: 100, // photos only默认为手机屏幕的宽，高与宽一样，为正方形照片
      maxHeight: 100, // photos only
      allowsEditing: true // 当用户选择过照片之后是否允许再次编辑图片
    };
    ImagePicker.launchCamera(options, response => {
      if (response.didCancel) {
        Toast.show("取消", 2000);
      } else if (response.error) {
        //('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        //('User tapped custom button: ', response.customButton);
      } else {
        let _data = [...this.state.images];
        _data.push(response.uri);
        this.setState({
          images: _data
        });
      }
    });
  }

  //开启相册
  launchImageLibrary() {
    if (this.state.images.length >= 10) {
      Toast.show("最多添加10张图片", 1000);
      return;
    }
    var options = {
      title: "图片来源", // 选择器的标题，可以设置为空来不显示标题
      cancelButtonTitle: "取消",
      takePhotoButtonTitle: "照相机", // 调取摄像头的按钮，可以设置为空使用户不可选择拍照
      chooseFromLibraryButtonTitle: "相册", // 调取相册的按钮，可以设置为空使用户不可选择相册照片
      mediaType: "photo", // 'photo' or 'video'
      maxWidth: 100, // photos only默认为手机屏幕的宽，高与宽一样，为正方形照片
      maxHeight: 100, // photos only
      allowsEditing: true // 当用户选择过照片之后是否允许再次编辑图片
    };
    ImagePicker.launchImageLibrary(options, response => {
      if (response.didCancel) {
        Toast.show("取消", 2000);
      } else if (response.error) {
        //('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        //('User tapped custom button: ', response.customButton);
      } else {
        let _data = [...this.state.images];
        _data.push(response.uri);
        this.setState({
          images: _data
        });
      }
    });
  }

  deleteImage = index => {
    const newData = [...this.state.images];
    newData.splice(index, 1);
    this.setState({ images: newData });
  };

  //如果有图片点击提交 先上传图片到七牛 获取uptoken
  getQiniuToken = () => {
    Loading.show();
    let { images } = this.state;
    if (images.length > 0) {
      requestApi
        .getQiniuToken()
        .then(res => {
          this.uploadimagetoQiniu(res);
        })
        .catch(err => {
          Loading.hide();
          Toast.show("图片上传token未取到", 1000);
        });
    } else {
      this.gocommint();
    }
  };

  //点击提交 先上传图片到七牛
  uploadimagetoQiniu = upToken => {
    let { images } = this.state;
    for (let i = 0; i < images.length; i++) {
      const params = {
        id: "555",
        filePath: images[i],
        upKey: null,
        upToken: upToken,
        zone: 3 //上传的区域写死3 包含http://up-z2.qiniu.com
      };
      QNEngine.setParams(params);
      // 开始上传任务
      QNEngine.startTask();
    }
  };

  //图片上传完成 开始提交内容
  gocommint = () => {
    //上传图片
    let { orderId } = this.props.navigation.state.params;
    let { pics, remarks } = this.state;
    requestApi
      .addPayPicAndRemarks({ orderId: orderId, pics: pics, remarks: remarks })
      .then(data => {
        Loading.hide();
        Toast.show("操作成功", 1000);
        NavigationService.navigate("PayRemarkScreen", { orderId: orderId });
      })
      .catch(err => {
        Loading.hide();
        Toast.show(err.msg, 1000);
      });
  };
}

const styles = StyleSheet.create({});

export default connect(
  ({ userInfo }) => ({
    userInfo
  }),
  {
    getLoginToken: actions.getLoginToken
  }
)(PayResultScreen);
